package com.hsck.order.kds.main.fragment.noodles

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.hsck.order.kds.R
import com.hsck.order.kds.base.isnoam.log.XFrame
import com.hsck.order.kds.base.utils.calculateMinutesSinceOrder
import com.hsck.order.kds.base.utils.setOnSingleClickListener
import com.hsck.order.kds.databinding.NoodlesAnVegetablesItemLayoutBinding
import com.hsck.order.kds.main.fragment.standard.bean.TestListBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class NoodlesAnVegetablesAdapter(val activity: Activity) :
    RecyclerView.Adapter<NoodlesAnVegetablesAdapter.ItemVH>() {

    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val viewHolders = mutableListOf<ItemVH>()
    private val diffUtil = object : DiffUtil.ItemCallback<TestListBean>() {
        override fun areItemsTheSame(oldItem: TestListBean, newItem: TestListBean): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: TestListBean, newItem: TestListBean): Boolean {
            return oldItem == newItem
        }
    }
    private val asyncListDiffer = AsyncListDiffer(this, diffUtil)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemVH {
        val viewHolder = ItemVH(
            NoodlesAnVegetablesItemLayoutBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
        viewHolders.add(viewHolder)
        return viewHolder
    }

    inner class ItemVH(val binding: NoodlesAnVegetablesItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {
        private var updateJob: Job? = null
        fun bindData(position: Int) {
            val item = asyncListDiffer.currentList[position]
            binding.viewDetail.setOnSingleClickListener {
                onDishOperationListener.onBatchOperationAction(item, position)
            }
            binding.tvTotalQuantity.setOnSingleClickListener {
                onDishOperationListener.onDishOperationAction(item, position)
            }
            updateJob = coroutineScope.launch {
                while (isActive) {
                    val time = calculateMinutesSinceOrder(item.time)
                    if (time != -1) {
                        if (time < 10) {
                            //正常
                            if (binding.tvDishZhengchang.tag != "enchanting") {
                                binding.tvDishZhengchang.visibility = View.GONE
                                binding.tvDishZhengchang.background =
                                    XFrame.getDrawable(R.drawable.blue_bg_shape)
                                binding.tvDishZhengchang.tag = "enchanting"
                            }
                        }
                        if (time in 11..19) {
                            // time大于10，小于20
                            //预警
                            if (binding.tvDishYujing.tag != "ring") {
                                binding.tvDishYujing.visibility = View.VISIBLE
                                binding.tvDishYujing.background =
                                    XFrame.getDrawable(R.drawable.orange_bg_shape)
                                binding.tvDishYujing.tag = "ring"
                            }
                        }
                        if (time > 19) {
                            if (binding.tvDishChaoshi.tag != "chaos") {
                                binding.tvDishChaoshi.visibility = View.VISIBLE
                                binding.tvDishChaoshi.background =
                                    XFrame.getDrawable(R.drawable.red_bg_shape)
                                binding.tvDishChaoshi.tag = "chaos"
                            }
                        }
                    }
                    delay(1000)
                }
            }
        }

        fun stopUpdating() {
            updateJob?.cancel()
            updateJob = null
        }
    }

    fun stopAllUpdating() {
        for (holder in viewHolders) {
            holder.stopUpdating()
        }
    }

    fun submitList(dataResponse: List<TestListBean>) {
        asyncListDiffer.submitList(dataResponse)
    }

    fun addItemAfterId(newItem: TestListBean, targetId: String) {
        val newList = asyncListDiffer.currentList.toMutableList()
        val targetIndex = newList.indexOfFirst { it.id == targetId }
        if (targetIndex != -1) {
            newList.add(targetIndex, newItem)
            asyncListDiffer.submitList(newList)
        }
    }

    fun removeItemAfterId(targetId: String) {
        val newList = asyncListDiffer.currentList.toMutableList()
        val targetIndex = newList.indexOfFirst { it.id == targetId }
        if (targetIndex != -1) {
            newList.removeAt(targetIndex)
            asyncListDiffer.submitList(newList)
        }
    }

    fun removeItemAfterIndex(targetIndex: Int) {
        if (targetIndex < asyncListDiffer.currentList.size) {
            val newList = asyncListDiffer.currentList.toMutableList()
            newList.removeAt(targetIndex)
            asyncListDiffer.submitList(newList)
        }
    }

    override fun onViewRecycled(holder: ItemVH) {
        super.onViewRecycled(holder)
        holder.stopUpdating()
        viewHolders.remove(holder)
    }


    override fun onBindViewHolder(holder: ItemVH, position: Int) {
        holder.bindData(position)
    }

    override fun getItemCount(): Int {
        return asyncListDiffer.currentList.size
    }


    private lateinit var onDishOperationListener: DishOperationListener
    fun setDishOperationListener(onDishOperationListener: DishOperationListener) {
        this.onDishOperationListener = onDishOperationListener
    }

    interface DishOperationListener {
        fun onBatchOperationAction(itemBean: TestListBean, position: Int)
        fun onDishOperationAction(itemBean: TestListBean, position: Int)
    }
}